from fastapi import APIRouter, Request, HTTPException
from typing import List, Optional
from config.database_connect import get_db_connection

appGetData = APIRouter()

# … 你已有的内容 …

@appGetData.get("/environment/chart")
async def get_environment_chart(request: Request, limit: int = 50):
    """
    获取当前用户最近 limit 条环境数据，用于折线图展示。
    返回字段包括时间戳 + 各指标。
    """
    user_id = request.session.get("user_id")
    if not user_id:
        raise HTTPException(status_code=401, detail="用户未登录")

    db = get_db_connection()
    if not db:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        with db.cursor() as cursor:
            sql = """
            SELECT upload_time, soil_moisture, soil_temperature, air_temperature, air_humidity, light_intensity
            FROM plant_data
            WHERE user_id = %s
            ORDER BY upload_time DESC
            LIMIT %s
            """
            cursor.execute(sql, (user_id, limit))
            rows = cursor.fetchall()
        # 将结果按时间升序（因为查询是降序）
        rows = list(reversed(rows))

        # 构建返回数据
        data = []
        for row in rows:
            data.append({
                "timestamp": row["upload_time"].isoformat() if hasattr(row["upload_time"], "isoformat") else str(row["upload_time"]),
                "soil_moisture": row["soil_moisture"],
                "soil_temperature": row["soil_temperature"],
                "air_temperature": row["air_temperature"],
                "air_humidity": row["air_humidity"],
                "light_intensity": row["light_intensity"],
            })

        return {
            "status": "success",
            "user_id": user_id,
            "count": len(data),
            "data": data,
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")
    finally:
        db.close()